package com.hoperun.framework.ibatis.page;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

public class PageRequest<T> implements Serializable {
	private static final long serialVersionUID = -5183965652108651634L;
	private T filters;
	private int pageNumber;
	private int pageSize;
	private String sortColumns;

	public PageRequest() {
		this.pageNumber = 0;
		this.pageSize = 0;
	}

	public PageRequest(T filtersParam) {
		this(0, 0, filtersParam);
		this.pageNumber = 0;
		this.pageSize = 0;
		setFilters(filtersParam);
	}

	public PageRequest(int number, int size) {
		this.pageNumber = number;
		this.pageSize = size;
		setFilters(null);
	}

	public PageRequest(int number, int size, T filtersParam) {
		this(number, size, filtersParam, null);
	}

	public PageRequest(int number, int size, String columns) {
		this(number, size, null, columns);
	}

	public PageRequest(int number, int size, T filtersParam, String columns) {
		this.pageNumber = number;
		this.pageSize = size;
		setFilters(filtersParam);
		setSortColumns(columns);
	}

	public T getFilters() {
		return this.filters;
	}

	public void setFilters(T filtersParam) {
		this.filters = filtersParam;
	}

	public int getPageNumber() {
		return this.pageNumber;
	}

	public void setPageNumber(int number) {
		this.pageNumber = number;
	}

	public int getPageSize() {
		return this.pageSize;
	}

	public void setPageSize(int size) {
		this.pageSize = size;
	}

	public String getSortColumns() {
		return this.sortColumns;
	}

	public void setSortColumns(String columns) {
		checkSortColumnsSqlInjection(columns);
		if ((columns != null) && (columns.length() > 50)) {
			throw new IllegalArgumentException(
					"sortColumns.length() <= 50 must be true");
		}
		this.sortColumns = columns;
	}

	public List<SortInfo> getSortInfos() {
		return Collections.unmodifiableList(SortInfo
				.parseSortColumns(this.sortColumns));
	}

	private void checkSortColumnsSqlInjection(String columns) {
		if (columns == null) {
			return;
		}
		if ((columns.indexOf('\'') >= 0) || (columns.indexOf('\\') >= 0)) {
			throw new IllegalArgumentException("sortColumns:" + columns
					+ " has SQL Injection risk");
		}
	}
}